<template>
    <div class="chart-main">
        <div class="chart-container">
            <canvas ref="humidityChartCanvas"></canvas>
        </div>
        <div class="chart-container">
            <canvas ref="temperatureChartCanvas"></canvas>
        </div>
        <div class="chart-container">
            <canvas ref="moistureChartCanvas"></canvas>
        </div>
        <div class="switch-container">
            <span>自动化开关</span>
            <el-switch v-model="value1" size="large" active-text="开" inactive-text="关" @change="sendCommand" />
            <span>水泵状态</span>
            <el-switch v-model="value2" size="large" active-text="开" inactive-text="关" @change="handleWater" :disabled="value1"/>
        </div>
    </div>
</template>

<script>
import { Line } from 'chart.js';
import Paho from 'paho-mqtt';

export default {
    name: 'LineChart',
    data() {
        return {
            mqttClient: null,
            dataQueue: [],
            // 用于存储空气湿度数据最新一次的消息数据 
            dataQueueSoil: [],
            airData: null,
            soilData: null,
            // 定时器ID，用于清除定时器  
            intervalId: null,
            humidityLine: null,
            temperatureLine: null,
            moistureLine: null,
            value1: true,
            value2: false,
        };
    },
    mounted() {
        this.renderLineChart();
        this.initMqttClient();
        this.startUpdatingChart();
    },
    methods: {
        renderLineChart() {
            const ctx = this.$refs.humidityChartCanvas.getContext('2d');
            this.humidityLine = new Line(ctx, {
                data: {
                    labels: [],
                    datasets: [{
                        label: '湿度',
                        data: [],
                        borderColor: 'rgb(75, 192, 192)',
                        tension: 0.2
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            const ctx2 = this.$refs.temperatureChartCanvas.getContext('2d');
            this.temperatureLine = new Line(ctx2, {
                data: {
                    labels: [],
                    datasets: [{
                        label: '温度',
                        data: [],
                        borderColor: 'rgb(255, 99, 132)',
                        tension: 0.5
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
            const ctx3 = this.$refs.moistureChartCanvas.getContext('2d');
            this.moistureLine = new Line(ctx3, {
                data: {
                    labels: [],
                    datasets: [{
                        label: '土壤湿度',
                        data: [],
                        borderColor: 'rgb(0,120,255)',
                        tension: 0.5
                    }]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        },
        updateQueue() {
            if (this.airData) {
                // 将新数据添加到队列队尾  
                this.dataQueue.push({
                    humidity: this.airData.AirMoisture,
                    temperature: this.airData.Temperature // 注意属性名大小写  
                });
                // 如果队列长度超过5，移除最旧的数据  
                if (this.dataQueue.length > 5) {
                    this.dataQueue.shift();
                }
                console.log('Updated Queue:', this.dataQueue);
            }
        },
        updateQueueSoil() {
            if (this.soilData) {
                // 将新数据添加到队列队尾  
                this.dataQueueSoil.push({
                    soilMoisture: this.soilData.Moisture,
                });
                // 如果队列长度超过5，移除最旧的数据  
                if (this.dataQueueSoil.length > 5) {
                    this.dataQueueSoil.shift();
                }
                console.log('Updated Queue Soil:', this.dataQueueSoil);
            }
        },
        initMqttClient() {
            const mqttWsUrl = 'ws://broker.emqx.io:8083/mqtt'; // 使用正确的 WebSocket 端口和可能的路径  
            this.mqttClient = new Paho.Client(mqttWsUrl, 'client-id-' + Math.random());
            this.mqttClient.onConnectionLost = this.onConnectionLost.bind(this)
            this.mqttClient.onMessageArrived = this.onMessageArrived.bind(this);
            var options = {
                timeout: 3,
                keepAliveInterval: 60,
                cleanSession: true,
                useSSL: false,
                onSuccess: this.onConnect.bind(this),
                onFailure: this.onFailure.bind(this)
            };
            this.mqttClient.connect(options);
        },
        onConnect() {
            console.log("Connected to MQTT broker");

            // 订阅第一个主题  
            this.mqttClient.subscribe("watering/Air", { qos: 0 });
            console.log("Subscribed to 'watering/Air'");

            // 订阅第二个主题  
            this.mqttClient.subscribe("watering/Soil", { qos: 0 });
            console.log("Subscribed to 'watering/Soil'");

            //订阅命令主题
            this.mqttClient.subscribe("watering/Command", { qos: 0 });
            console.log("Subscribed to 'watering/Water'");

            // 订阅水泵主题  
            this.mqttClient.subscribe("watering/Water", { qos: 0 });
            console.log("Subscribed to 'watering/Water'");
        },
        onConnectionLost(responseObject) {
            console.log("onConnectionLost:" + responseObject.errorCode);
        },
        onMessageArrived(message) {
            if (message.destinationName === "watering/Air") {
                // 处理空气湿度数据
                try {

                    this.airData = JSON.parse(message.payloadString);
                    this.updateQueue();
                } catch (error) {
                    console.error('Error parsing MQTT message:', error);
                }
            }
            else if (message.destinationName === "watering/Soil") {
                // 处理土壤湿度数据
                try {
                    this.soilData = JSON.parse(message.payloadString);
                    this.updateQueueSoil();
                } catch (error) {
                    console.error('Error parsing MQTT message:', error);
                }
            }
            else if (message.destinationName === "watering/Command") {
                // 处理自动化开关
                try {
                    const water = JSON.parse(message.payloadString);
                    this.value1 = this.commandValue(water.command)
                    console.log('Received command:', water.command, this.value1)
                } catch (error) {
                    console.error('Error parsing MQTT message:', error);
                }
            }
            else if (message.destinationName === "watering/Water") {
                // 处理水泵开关
                try {
                    const water = JSON.parse(message.payloadString);
                    this.value2 =this.commandValue(water.command)
                    console.log('Received water command:', water.command,this.value2)
                } catch (error) {
                    console.error('Error parsing MQTT message:', error);
                }
            }
        },
        onFailure(message) {
            console.log("onFailure:" + message.errorMessage);
        },
        startUpdatingChart() {
            this.intervalId = setInterval(() => {
                this.updateChartData();
            }, 10000);
        },
        updateChartData() {
            const labels = this.dataQueue.map((_, index) => (`${index + 1}`).padStart(2, '0'));
            const labelsSoil = this.dataQueueSoil.map((_, index) => (`${index + 1}`).padStart(2, '0'));
            const humidityData = this.dataQueue.map(item => item.humidity);
            const temperatureData = this.dataQueue.map(item => item.temperature);
            const soilData = this.dataQueueSoil.map(item => item.soilMoisture);
            this.humidityLine.data.labels = labels.slice(-5);
            this.humidityLine.data.datasets[0].data = humidityData.slice(-5);
            this.temperatureLine.data.labels = labels.slice(-5);
            this.temperatureLine.data.datasets[0].data = temperatureData.slice(-5);
            this.moistureLine.data.labels = labelsSoil.slice(-5);
            this.moistureLine.data.datasets[0].data = soilData.slice(-5);

            // 重新渲染图表  
            this.humidityLine.update();
            this.temperatureLine.update();
            this.moistureLine.update();
        },
        commandValue(command) {
            if (command === 'start') {
                return true;
            } else if (command === 'stop') {
                return false;
            } else {
                return this.value1;
            }
        },
        sendCommand() {// 发送自动化开关命令
            if (this.mqttClient && this.mqttClient.isConnected()) {
                const nowCommand = this.value1 ? 'start' : 'stop';
                const message = JSON.stringify({ command: nowCommand });
                this.mqttClient.publish('watering/Command', message);
                console.log(`Sent command ${nowCommand} as JSON to watering/Command`);
            } else {
                console.log('MQTT client not connected');
            }
        },
        handleWater() {// 发送手动开关命令
            if (this.mqttClient && this.mqttClient.isConnected()) {
                const nowCommand = this.value2 ? 'start' : 'stop';
                const message = JSON.stringify({ command: nowCommand });
                this.mqttClient.publish('watering/Water', message);
                console.log(`Sent command ${nowCommand} as JSON to watering/Water`);
            } else {
                console.log('MQTT client not connected');
            }
        },
    },
    beforeUnmount() {
        clearInterval(this.intervalId); // 清除定时器  
        if (this.mqttClient && this.mqttClient.isConnected()) {
            this.mqttClient.disconnect();
        }
    },
};
</script>
<style>
.chart-main {
    display: flex;
    flex-wrap: wrap;
    /* 允许项目换行 */
    justify-content: left;
}

.chart-container {
    margin: 10px;
    width: calc(100% - 20px);
    /* 减去两边边距 */
    height: 300px;

    /* 可以添加媒体查询来进一步调整 */
    @media (min-width: 600px) {
        width: calc(50% - 20px);
        /* 在较宽的屏幕上并排显示两个图表 */
    }

    @media (min-width: 900px) {
        width: calc(33.3333% - 20px);
        /* 在更宽的屏幕上并排显示三个图表 */
    }
}

.switch-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 10px;
}

.switch-container span {
    margin-bottom: 10px;
}
</style>